package com.lagou.edu.controller;

import com.lagou.edu.service.user.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code){
        return userService.register(email,password,code);
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        return userService.isRegistered(email);
    }

    @PostMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response){
        String token = userService.login(email, password);
        if (StringUtils.isNotBlank(token)){
            Cookie token1 = new Cookie("token", token);
            token1.setPath("/");
            response.addCookie(token1);
        }
        return email;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token){
        return userService.info(token);
    }
}
